var express = require("express");
var router = express.Router();
// var async = require("async");
const comment = require("../model/comment");
const comfabulous = require("../model/comfabulous");
const answer = require("../model/answer");
const problem = require("../model/problem");
router.post("/api/v1/getproposal", async (req, res) => {
    try {
        let problemData = problem.find({audit:true}).populate([{path:"userid"}, {path:"adopt",populate: {path: 'userid',populate:{path:'department'}}}]).sort({_id:-1});
        if (req.body.sort) {
          problemData.sort(req.body.sort);
        }
      
        if (req.body.skip) {
          problemData.skip(req.body.skip);
        }
        if (req.body.limit) {
          problemData.limit(req.body.limit);
        }
        let result = await problemData.exec();
        for (let index = 0; index < result.length; index++) {
          let answercount = await answer.find({problem_id:result[index]._id}).count()
          result[index]._doc.anscount = answercount;
          let img = null;
          if(result[index].adopt){
            img = result[index].adopt.content.match(/src="(\S*)"/ig)
          }
          if(img!=null){
                let name = img[0].replace('src="',"");
                let imgname = name.substring(0, name.length - 1);
                result[index]._doc.answerimg = imgname
            }
        }
        res.json({
          code: 200,
          data: result,
        });
    } catch (error) {
        console.log(error)
        res.json({
            code: 400,
            data: error,
          });
    }


});

// 导出模块（在 app.js 中引入）
module.exports = router;